package insight.threadpool;

import Jvm.A;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class MyThreadPool {

    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1024);

    private final Runnable task = () -> {
        while (true) {
            try {
                Runnable command = blockingQueue.take();
                command.run();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    };

    Thread thread = new Thread(() -> {
        while (true) {
            try {
                Runnable command = blockingQueue.take();
                command.run();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }, "唯一线程");

    {
        thread.start();
    }

    private int corePoolSize = 10;
    private int maxSize = 16;
    List<Thread> coreList = new ArrayList<>();
    List<Thread> supportList = new ArrayList<>();
    void execute(Runnable command){
        if (coreList.size() < corePoolSize) {
            Thread thread = new Thread(task);
            coreList.add(thread);
            thread.start();
        }

        if (blockingQueue.offer(command)) {
            return;
        }

        if (coreList.size() + supportList.size() < maxSize) {
            Thread thread = new Thread(task);
            supportList.add(thread);
            thread.start();
        }

    }
}
